import { createClient } from "~/lib/supabase/client";

import { resolveServiceURL } from "./resolve-service-url";

// 上传进度回调类型
export type UploadProgressCallback = (progress: number) => void;

// 通用上传请求类型
export interface UploadRequest {
  file: File;
  onProgress: UploadProgressCallback;
  params?: Record<string, string>;
}

// 通用上传响应类型
export interface UploadResponse {
  success: boolean;
}

// 通用文件上传函数
export async function uploadFile(
  endpoint: string,
  file: File,
  params?: Record<string, string>,
  onProgress?: UploadProgressCallback,
): Promise<UploadResponse> {
  // 文件大小验证（100MB 限制）
  const MAX_FILE_SIZE = 100 * 1024 * 1024;
  if (file.size > MAX_FILE_SIZE) {
    throw new Error(`文件大小不能超过 ${MAX_FILE_SIZE / 1024 / 1024}MB`);
  }

  // 创建 FormData 对象
  const formData = new FormData();
  formData.append("file", file);

  // 添加额外数据
  if (params) {
    Object.entries(params).forEach(([key, value]) => {
      formData.append(key, value);
    });
  }

  const supabase = createClient();
  const {
    data: { session },
  } = await supabase.auth.getSession();

  // 创建 XMLHttpRequest 以支持进度回调
  if (onProgress) {
    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();

      xhr.upload.addEventListener("progress", (event) => {
        if (event.lengthComputable) {
          const progress = (event.loaded / event.total) * 100;
          onProgress(progress);
        }
      });

      xhr.addEventListener("load", () => {
        if (xhr.status >= 200 && xhr.status < 300) {
          try {
            const response = JSON.parse(xhr.responseText);
            resolve(response);
          } catch (error) {
            console.log("响应解析失败", error);
            reject(new Error("响应解析失败"));
          }
        } else {
          reject(new Error(`上传失败: ${xhr.statusText}`));
        }
      });

      xhr.addEventListener("error", () => {
        reject(new Error("网络错误"));
      });

      xhr.open("POST", resolveServiceURL(endpoint));
      // 添加 Authorization header
      if (session?.access_token) {
        xhr.setRequestHeader("Authorization", `Bearer ${session.access_token}`);
      }
      xhr.send(formData);
    });
  }

  // 使用 fetch API（无进度回调）
  const response = await fetch(resolveServiceURL(endpoint), {
    method: "POST",
    // 不要设置 Content-Type，让浏览器自动设置 multipart/form-data
    headers: {
      Authorization: `Bearer ${session?.access_token}`,
    },
    body: formData,
  });

  if (!response.ok) {
    const errorText = await response.text();
    throw new Error(
      `上传失败: ${response.status} ${response.statusText} - ${errorText}`,
    );
  }

  return await response.json();
}

// Type definition for the upload function
export type UploadFunction = ({
  file,
  onProgress,
  params,
}: UploadRequest) => Promise<UploadResponse>;

// 面试相关上传参数类型
export interface UploadInterviewParams extends Record<string, string> {
  thread_id: string;
  agent_code: string;
  upload_type: "resume" | "interview_record";
}

export const uploadInterview: UploadFunction = ({
  file,
  onProgress,
  params,
}) => {
  return uploadFile("upload_interview", file, params, onProgress);
};
